﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Xpo;

namespace RemoteImaging.LicensePlate
{
    public class CarCountUpdater
    {
        private List<DateTime> _carDateTimes = new List<DateTime>();

        public int CountToUpdate { get; set; }

        public CarCountUpdater()
        {
            CountToUpdate = 10;
        }

        public void HandleCarCountByHour(IEnumerable<LicensePlateInfo> lpis)
        {
            if (lpis == null)
                throw new ArgumentNullException("lpis", "lpis is null.");

            _carDateTimes.AddRange(lpis.Select(lpi => lpi.CaptureTime.Date.AddHours(lpi.CaptureTime.Hour)));

            if (_carDateTimes.Count >= CountToUpdate)
            {
                AddOrUpdateCarCountByHour(_carDateTimes);
                _carDateTimes.Clear();
            }
        }

        private void AddOrUpdateCarCountByHour(List<DateTime> _carDateTimes)
        {
            var q = from t in _carDateTimes
                    group t by t into g
                    select new { Time = g.Key, Count = g.Count() };

            using (var uow = new UnitOfWork())
            {
                foreach (var item in q)
                {
                    var carCount = Helper.FindCarCountByTime(item.Time, uow);
                    if (carCount == null)
                    {
                        carCount = new CarCountPerHour(uow) { Time = item.Time };
                    }
                    carCount.Count += item.Count;
                    carCount.Save();
                }

                uow.CommitChanges();

            }
        }


    }
}
